var config = require('../../config');
var OAuth = require('wechat-oauth');
var jsapiTicketController = require('./JsapiTicketController');
var sign = require('../../common/utils/sign.js');
var logger = require('../../common/Logger/Logger');
var cinemaDao = require('../dao/CinameDao');
var moment = require('moment');

var wechatAPI = require('wechat-api');
var api = new wechatAPI(config.app.appid, config.app.appsecret);

var client = new OAuth(config.app.appid, config.app.appsecret);

var queryConfig = function (callback, req) {
    var url = req.protocol + '://' + req.host + req.originalUrl; //获取当前url
    var ret = sign(jsapiTicketController.getJsapiTicket(), url);
    console.log(ret);
    callback(ret);
};

module.exports.setConfig = function (req, res) {
    var cookie_openid;
    if(req.signedCookies.openid){
        cookie_openid = req.signedCookies.openid;
        queryConfig(function (ret) {
            res.render('scan', {
                title: '请扫码绑定影厅',
                layout: 'index',
                sign_pkg: ret.jsapi_ticket,
                appId: config.app.appid,
                timestamp: ret.timestamp,
                nonceStr: ret.nonceStr,
                signature: ret.signature,
                open_id: cookie_openid
            });
        }, req);


    }else{
        client.getAccessToken(req.query.code, function (err, result) {
            if(err){
                console.log(err);
                res.render('error',{
                    title: '微信连接超时，请重试！',
                    message:err,
                    layout: 'index'});
            }else{
                //var accessToken = result.data.access_token;
                var openid = result.data.openid;
                res.cookie('openid', openid, {maxAge:1000*60*60*24,signed:true});
                queryConfig(function (ret) {
                    res.render('scan', {
                        title: '请扫码绑定影厅',
                        layout: 'index',
                        sign_pkg: ret.jsapi_ticket,
                        appId: config.app.appid,
                        timestamp: ret.timestamp,
                        nonceStr: ret.nonceStr,
                        signature: ret.signature,
                        open_id: openid
                    });
                }, req);
            }

        });
    }
};

module.exports.sendTextMsg = function (req, res) {
    var now = moment();
    var ipd = req.body.ipd;
    var roomid = req.body.roomid;
    var open_id = req.body.open_id;
    var networktype = req.body.networktype;
    var cinemacd = req.body.cinemacd;
    var roomname = req.body.roomname=='undefined'?'':req.body.roomname;

    if(networktype!='1'){
        res.send({error: '1',message: '必须使用影吧WIFI连接！'});
    }else if(ipd==null || ipd=='' || ipd=='undefined'){
        res.send({error: '1',message: '二维码错误！'});
    }else{
        var myurl = 'http://'+ipd+'/?roomid='+roomid;
        if(cinemacd==null || cinemacd=='' || cinemacd=='undefined'){
            var textMsg = '******** 快捷服务 ********\r\n- 点播请戳：<a href=\"'+ myurl+'&openid=' + open_id+ '\">打开遥控器</a>\r\n- 绑定时间：'+ moment().format('MM-DD HH:mm')+'\r\n' +
                '- <a href=\"http://mp.weixin.qq.com/s/OmaU9CwADwcmv-JjjNAYoA\">新手指引</a>'+
                '\r\n******** 快捷服务 ********';
            api.sendText(open_id,textMsg ,function (err, result) {
                if (err) {
                    //res.send({error: '1',message: 'fail'});
                    res.send({error: '0',message: 'success'});
                    logger.info(err);
                } else {
                    res.send({error: '0',message: 'success'});
                }
            });
        }else{
            cinemaDao.getCinemaInfoByCode(cinemacd, function (data) {
                if (data.isSuccess) {
                    var conccinemaname='';
                    if(data.rows.length > 0 ){
                        conccinemaname=data.rows[0].cinema_name
                    }
                    var concroomname='';
                    if(roomname!=null && roomname!='' && roomname!='undefined'){
                        concroomname = '\r\n- 影厅：'+decodeURIComponent(decodeURIComponent(roomname));
                    }
                    if(conccinemaname!=null && conccinemaname!='' && conccinemaname!='undefined'){
                        conccinemaname = '\r\n- 点播影院：'+ conccinemaname;
                    }
                    var textMsg = '******** 快捷服务 ********'+conccinemaname+concroomname+'\r\n- 点播请戳：<a href=\"'+ myurl+'&openid=' + open_id+ '\">打开遥控器</a>\r\n- 绑定时间：'+ moment().format('MM-DD HH:mm')+'\r\n' +
                        '- <a href=\"http://mp.weixin.qq.com/s/OmaU9CwADwcmv-JjjNAYoA\">新手指引</a>'+
                        '\r\n******** 快捷服务 ********';
                    api.sendText(open_id,textMsg ,function (err, result) {
                        if (err) {
                            //res.send({error: '1',message: 'fail'});
                            res.send({error: '0',message: 'success'});
                            logger.info(err);
                        } else {
                            res.send({error: '0',message: 'success'});
                        }
                    });
                } else {
                    //
                }
            });
        }

    }

};
